<script setup lang="ts">
import {
  getPatientList,
  addPatient,
  updatePatient,
  deletePatient
} from '@/services/user'
import type { Patient } from '@/types/user'
import { onMounted, ref, computed } from 'vue'
import { nameRules, idCardRules } from '@/utils/rules'
import { showConfirmDialog, showSuccessToast, showToast } from 'vant'
import type { FormInstance } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { useConsultStore } from '@/stores/modules/consult'

const list = ref<Patient[]>([])

const getList = async () => {
  const res = await getPatientList()
  list.value = res.data
}

onMounted(async () => {
  await getList()
  await changeDefaut()
})

const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]
const showRight = ref(false)
const showPupup = (item?: Patient) => {
  if (item) {
    // 填充表单
    const { id, idCard, name, gender, defaultFlag } = item
    patient.value = { id, idCard, name, gender, defaultFlag }
  } else {
    // 重置弹窗数据
    patient.value = { ...initPatient }
  }
  showRight.value = !showRight.value
}
// 表单数据
const initPatient: Patient = {
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0
}
const patient = ref<Patient>({ ...initPatient })

const difaultFlag = computed({
  get() {
    return patient.value.defaultFlag === 1
  },
  set(value) {
    patient.value.defaultFlag = value ? 1 : 0
  }
})

const form = ref<FormInstance>()
const submit = async () => {
  try {
    await form.value?.validate()
    const gender = +patient.value.idCard.slice(-2, -1) % 2
    if (gender != patient.value.gender) {
      await showConfirmDialog({
        title: '温馨提示',
        message: '填写的性别和身份证号中的不一致\n您确认提交吗?'
      })
    }
    patient.value.id
      ? await updatePatient(patient.value)
      : await addPatient(patient.value)
    showRight.value = false
    getList()
    showSuccessToast(patient.value.id ? '编辑成功' : '添加成功')
  } catch (error) {
    console.log()
  }
}
const remove = async () => {
  if (patient.value.id) {
    await showConfirmDialog({
      title: '温馨提示',
      message: '确认删除患者信息?'
    })
    await deletePatient(patient.value.id)
    showRight.value = false
    getList()
    showSuccessToast('删除成功')
  }
}

const route = useRoute()

const isChange = computed(() => route.query.isChange === '1')
const patientId = ref<string>()
const select = (item: Patient) => {
  if (isChange.value) {
    patientId.value = item.id
  }
}

const changeDefaut = () => {
  if (isChange.value && list.value.length) {
    const def = list.value.find((item) => item.defaultFlag)
    if (def) {
      patientId.value = def.id
    } else {
      patientId.value = list.value[0].id
    }
  }
}

const store = useConsultStore()
const router = useRouter()
const next = () => {
  if (!patientId.value) return showToast('请选择患者')
  store.setPatient(patientId.value)
  router.push('/consult/pay')
}
</script>
<template>
  <div class="patient-page">
    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'"></cp-nav-bar>
    <!-- 头部提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <div class="patient-list">
      <div
        class="patient-item"
        :class="{ selected: patientId == item.id }"
        v-for="item in list"
        :key="item.id"
        @click="select(item)"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <span class="id">{{
            item.idCard.replace(/^(.{6}).+(.{4})$/, '\$1********\$2')
          }}</span>
          <span>{{ item.genderValue }}</span>
          <span>{{ item.age }}岁</span>
        </div>
        <div class="icon">
          <cp-icon name="user-edit" @click="showPupup(item)"></cp-icon>
        </div>
        <div class="tag" v-if="item.defaultFlag">默认</div>
      </div>
      <div class="patient-add" v-if="list.length < 6" @click="showPupup()">
        <cp-icon name="user-add"></cp-icon>
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加6人</div>
    </div>
    <!-- 右侧弹出 -->
    <van-popup v-model:show="showRight" position="right">
      <cp-nav-bar
        :back="() => (showRight = !showRight)"
        :title="patient.id ? '编辑患者' : '添加患者'"
        right-text="保存"
        @click-right="submit"
      ></cp-nav-bar>
      <van-form autocomplete="off" ref="form">
        <van-field
          label="姓名"
          v-model="patient.name"
          placeholder="请输入姓名"
          :rules="nameRules"
        ></van-field>
        <van-field
          v-model="patient.idCard"
          label="身份证号"
          placeholder="请输入身份证号"
          :rules="idCardRules"
        ></van-field>
        <van-field label="性别" class="pb4">
          <template #input>
            <cp-radio-btn
              v-model="patient.gender"
              :options="options"
            ></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox
              v-model="difaultFlag"
              :icon-size="18"
              round
            ></van-checkbox>
          </template>
        </van-field>
      </van-form>
      <van-action-bar v-if="patient.id && !patient.defaultFlag">
        <van-action-bar-button @click="remove">删除</van-action-bar-button>
      </van-action-bar>
    </van-popup>

    <div class="patient-next" v-if="isChange">
      <van-button type="primary" round block @click="next">下一步</van-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.patient {
  &-page {
    padding: 46px 0 80px;
    :deep(.van-popup) {
      width: 100%;
      height: 100%;
      padding-top: 46px;
      box-sizing: border-box;
    }
    .van-action-bar {
      padding: 0 10px;
      margin-bottom: 10px;
      .van-button {
        color: var(--cp-price);
        background-color: var(--cp-bg);
      }
    }
  }
  &-list {
    padding: 15px;
  }
  &-item {
    display: flex;
    align-items: center;
    padding: 15px;
    background-color: var(--cp-bg);
    border-radius: 8px;
    margin-bottom: 15px;
    position: relative;
    border: 1px solid var(--cp-bg);
    transition: all 0.3s;
    overflow: hidden;
    .info {
      display: flex;
      flex-wrap: wrap;
      flex: 1;
      span {
        color: var(--cp-tip);
        margin-right: 20px;
        line-height: 30px;
        &.name {
          font-size: 16px;
          color: var(--cp-text1);
          width: 80px;
          margin-right: 0;
        }
        &.id {
          color: var(--cp-text2);
          width: 180px;
        }
      }
    }
    .icon {
      color: var(--cp-tag);
      width: 20px;
      text-align: center;
    }
    .tag {
      position: absolute;
      right: 60px;
      top: 21px;
      width: 30px;
      height: 16px;
      font-size: 10px;
      color: #fff;
      background-color: var(--cp-primary);
      border-radius: 2px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    &.selected {
      border-color: var(--cp-primary);
      background-color: var(--cp-plain);
      .icon {
        color: var(--cp-primary);
      }
    }
  }
  &-add {
    background-color: var(--cp-bg);
    color: var(--cp-primary);
    text-align: center;
    padding: 15px 0;
    border-radius: 8px;
    .cp-icon {
      font-size: 24px;
    }
  }
  &-tip {
    color: var(--cp-tag);
    padding: 12px 0;
  }
  &-change {
    padding: 15px;
    > h3 {
      font-weight: normal;
      margin-bottom: 5px;
    }
    > p {
      color: var(--cp-text3);
    }
  }
  &-next {
    padding: 15px;
    background-color: #fff;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 80px;
    box-sizing: border-box;
  }
}
</style>
